package com.lenovo.smarttraffic.ui.activity.stage4;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.BusLineInfoBean;
import com.lenovo.smarttraffic.bean.BusLineOrderBean;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.Utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomBusActivity extends BaseActivity {

    public static List<BusLineInfoBean.ROWSDETAILBean> beanList;

    public static List<BusLineOrderBean.ROWSDETAILBean> orderBeanList;

    private Toolbar toolbar;
    private ImageView qr_img;
    private TextView order_tv;

    private ExpandableListView listView;

    private Handler handler = new Handler();

    private Gson gson = new Gson();


    @Override
    protected int getLayout() {
        return R.layout.activity_custom_bus;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        toolbar = findViewById(R.id.toolbar);
        toolbar.setNavigationOnClickListener(v -> finish());

        qr_img = findViewById(R.id.qr_img);
        order_tv = findViewById(R.id.order_tv);

        listView = findViewById(R.id.ex_listView);

        initData();
    }

    private void initData() {
        HttpUtils.post("get_busline_info", new HttpUtils().setParam("UserName", MainActivity.userName),
                response -> {
                    BusLineInfoBean busLineInfoBean = new Gson().fromJson(response.toString(), BusLineInfoBean.class);
                    beanList = busLineInfoBean.getROWS_DETAIL();

                    listView.setAdapter(new CustomBusAdapter());
                    listView.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> {
                        Intent intent = new Intent(this, BusOrderActivity.class);
                        intent.putExtra("pos", groupPosition);
                        startActivity(intent);
                        return true;
                    });
                });

        HttpUtils.post("get_busline_order", new HttpUtils().setParam("UserName", MainActivity.userName),
                response -> {
                    BusLineOrderBean busLineInfoBean = gson.fromJson(response.toString(), BusLineOrderBean.class);
                    orderBeanList = busLineInfoBean.getROWS_DETAIL();

                    if (orderBeanList.size() > 1) {
                        for (int i = 0; i < orderBeanList.size(); i++) {
                            BusLineOrderBean.ROWSDETAILBean bean = orderBeanList.get(i);
                            if (bean.getFlag() == 1) {//判断是否已支付
                                Map<String, Object> map = new HashMap<>(5);
                                map.put("UserName", bean.getUser());
                                map.put("Id", new String[]{"" + bean.getId(), "" + bean.getBus_id(), "" + bean.getFlag()});

                                String qr_info = gson.toJson(map);
                                qr_img.setImageBitmap(Utils.createQRCodeImage(qr_info, 40, 40));
                                qr_img.setOnClickListener(v -> {
                                    View view = View.inflate(this, R.layout.dialog_qr_code, null);
                                    TextView info_tv = view.findViewById(R.id.info_tv);
                                    info_tv.setText(qr_info);
                                    ImageView image = view.findViewById(R.id.image);
                                    image.setImageBitmap(Utils.createQRCodeImage(qr_info + "\n" + System.currentTimeMillis(), 500, 500));
                                    refresh(qr_info, image);
                                    image.setOnLongClickListener(v1 -> {
                                        info_tv.setVisibility(info_tv.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                                        return true;
                                    });
                                    new AlertDialog.Builder(this)
                                            .setTitle("身份识别")
                                            .setView(view)
                                            .setPositiveButton("确定", null)
                                            .show();
                                });
                                break;
                            }
                        }
                    }
                    order_tv.setOnClickListener(v -> startActivity(new Intent(this, MyOrderActivity.class)));
                });
    }

    private void refresh(String qr_info, ImageView imageView) {
        handler.postDelayed(() -> {
            if (imageView != null) {
                imageView.setImageBitmap(Utils.createQRCodeImage(qr_info + "\n" + System.currentTimeMillis(), 500, 500));
                refresh(qr_info, imageView);
            }
        }, 3000);
    }

}

class CustomBusAdapter extends BaseExpandableListAdapter {

    public static List<BusLineInfoBean.ROWSDETAILBean> list = CustomBusActivity.beanList;

    public CustomBusAdapter() {
    }

    @Override
    public int getGroupCount() {
        return list.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return 1;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return list.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return null;
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        //分组和子选项是否持有稳定的ID, 就是说底层数据的改变会不会影响到它们
        return true;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        GroupViewHolder viewHolder;

        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.exlist_subway_group, parent, false);
            viewHolder = new GroupViewHolder();
            viewHolder.id_tv = convertView.findViewById(R.id.id_tv);
            viewHolder.point_tv = convertView.findViewById(R.id.point_tv);
            viewHolder.time_tv = convertView.findViewById(R.id.time_tv);
            viewHolder.expand = convertView.findViewById(R.id.expand);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (GroupViewHolder) convertView.getTag();
        }

        BusLineInfoBean.ROWSDETAILBean bean = list.get(groupPosition);

        viewHolder.id_tv.setText(bean.getId() + "号线");
        viewHolder.point_tv.setText(bean.getStart_place() + "————" + bean.getEnd_place() + "\n" +
                "票价：￥" + bean.getPrice() + "  里程：" + bean.getDistance() + "km");
        viewHolder.time_tv.setText("🕓" + bean.getStart_place_start_time() + "-" + bean.getStart_place_end_time() + "\n" +
                "🕓" + bean.getEnd_place_start_time() + "-" + bean.getEnd_place_end_time());

        //如果是展开状态，
        if (isExpanded) {
            viewHolder.expand.setRotation(270);
        } else {
            viewHolder.expand.setRotation(180);
        }

        return convertView;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ChildViewHolder viewHolder;

        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.exlist_subway_child, parent, false);
            viewHolder = new ChildViewHolder();
            viewHolder.roads_tv = convertView.findViewById(R.id.roads_tv);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ChildViewHolder) convertView.getTag();
        }

        BusLineInfoBean.ROWSDETAILBean bean = list.get(groupPosition);

        viewHolder.roads_tv.setText(bean.getStart_place() + "\n" +
                bean.getBus_stop().replace(",", "\n") +
                bean.getEnd_place());

        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        //指定位置上的子元素是否可选中
        return true;
    }

    static class GroupViewHolder {
        TextView id_tv, point_tv, time_tv;
        View expand;
    }

    static class ChildViewHolder {
        TextView roads_tv;
    }
}
